import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 添加请求拦截器，自动包含Token
instance.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 定义状态码常量
const STATUS_MESSAGES: { [key: string]: string } = {
  '400': '请求错误',
  '401': '未授权',
  '403': '禁止访问',
  '404': '未找到',
  '415': '不支持的媒体类型',
  '500': '服务器错误',
  '503': '服务不可用',
}

// 提取错误信息处理函数
function handleErrorResponse(status: number, response: any): string {
  return (
    response.data.detail || STATUS_MESSAGES[status.toString()] || `未知错误：${response.message}`
  )
}

// 添加响应拦截器，根据状态码输出报错原因
instance.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      const status = error.response.status
      const errorMessage = handleErrorResponse(status, error.response)
      if (errorMessage.includes('过期')) {
        localStorage.removeItem('token')
        window.location.reload()
      }
      ElMessage.error({
        message: errorMessage,
        duration: 6000,
      })
      console.error(errorMessage)
    } else {
      const networkErrorMessage = '网络错误：无法连接到服务器。'
      console.error(networkErrorMessage)
      ElMessage.error(networkErrorMessage)
      // 弹出是否刷新
      ElMessageBox.confirm(networkErrorMessage + '是否刷新页面？', '提示', {
        confirmButtonText: '刷新',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        window.location.reload()
      })
    }

    return Promise.reject(error)
  }
)

export default instance
